package com.longyou.gateway.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@ConditionalOnProperty(prefix = "spring.cloud.gateway.swagger", name = "disabled", havingValue = "true")
public class SwaggerBlockFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();
        if (path.matches(".*?/doc.html.*") ||
            path.matches(".*?/swagger.*") ||
            path.matches(".*?/v2/api-docs.*") ||
            path.matches(".*?/v3/api-docs.*") ||
            path.matches(".*?/swagger-ui.html.*") ||
            path.matches(".*?/swagger-resources.*")) {
            exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
